package com.module.umlib.umeng;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.Map;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

public class UmengFragment extends Fragment {

    private static String TAG = "UmengFragment";
    private BehaviorSubject<Umeng> mObservable;

    public static UmengFragment newInstance(FragmentActivity activity) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();

        UmengFragment umengFragment = (UmengFragment) fragmentManager.findFragmentByTag(TAG);
        boolean isNewInstance = umengFragment == null;
        if (isNewInstance) {
            umengFragment = new UmengFragment();
            fragmentManager
                    .beginTransaction()
                    .add(umengFragment, TAG)
                    .commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }

        return umengFragment;
    }

    public IRxUmeng createObservable() {
        mObservable = BehaviorSubject.create();
        return new IRxUmeng() {
            @Override
            public Observable<Umeng> umAuthLogin(SHARE_MEDIA shareMedia) {
                UMShareConfig config = new UMShareConfig();
                config.isNeedAuthOnGetUserInfo(true);
                //当安装的时候进行SSO授权,还有一种网页授权,无论设备上是否按照微博客户端,都只会拉起网页授权
                config.setSinaAuthType(UMShareConfig.AUTH_TYPE_SSO);
                UMShareAPI umShareAPI = UMShareAPI.get(getContext());
                umShareAPI.setShareConfig(config);
                umShareAPI.getPlatformInfo(getActivity(), shareMedia, umAuthListener);
                return mObservable;
            }

            @Override
            public Observable<Umeng> umShare(SHARE_MEDIA shareMedia, String shareUrl, String shareImageUrl, String shareTitle, String shareContent) {
                if ((shareMedia.equals(SHARE_MEDIA.WEIXIN) || shareMedia.equals(SHARE_MEDIA.WEIXIN_CIRCLE)) && !checkIsInstallWeiXin()) {
                    mObservable.onComplete();
                    return mObservable;
                }
                if ((shareMedia.equals(SHARE_MEDIA.QQ) || shareMedia.equals(SHARE_MEDIA.QZONE)) && !checkIsInstallQQ()) {
                    mObservable.onComplete();
                    return mObservable;
                }

                ShareAction shareAction = new ShareAction(getActivity()); //分享面板
                UMWeb umWeb = new UMWeb(shareUrl); //切记切记 这里分享的链接必须是http开头
                umWeb.setTitle(shareTitle);//标题
                umWeb.setThumb(getShareImage(shareImageUrl));  //缩略图
                umWeb.setDescription(shareContent);//描述

                shareAction.withMedia(umWeb);
                shareAction.setPlatform(shareMedia);
                shareAction.setCallback(umShareListener);
                shareAction.share();
                return mObservable;
            }

        };
    }

    /**
     * auth回调
     */
    UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if (data == null) {
                Toast.makeText(getContext(), "没有用户信息", Toast.LENGTH_SHORT).show();
                return;
            }
            mObservable.onNext(new Umeng(platform, action, data));
            mObservable.onComplete();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            if (platform.equals(SHARE_MEDIA.QQ)) {
                Toast.makeText(getContext(), "已取消QQ登录", Toast.LENGTH_SHORT).show();
            } else if (platform.equals(SHARE_MEDIA.WEIXIN)) {
                Toast.makeText(getContext(), "已取消微信登录", Toast.LENGTH_SHORT).show();
            } else if (platform.equals(SHARE_MEDIA.SINA)) {
                Toast.makeText(getContext(), "已取消微博登录", Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 分享回调
     */
    UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            mObservable.onNext(new Umeng(platform));
            mObservable.onComplete();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getContext(), "分享失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), "分享取消", Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 检测是否安装微信
     *
     * @return
     */
    private boolean checkIsInstallWeiXin() {
        if (!UMShareAPI.get(getContext()).isInstall(getActivity(), SHARE_MEDIA.WEIXIN)) {
            Toast.makeText(getContext(), "您还未安装微信客户端!", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检测是否安装QQ
     *
     * @return
     */
    private boolean checkIsInstallQQ() {
        if (!UMShareAPI.get(getContext()).isInstall(getActivity(), SHARE_MEDIA.QQ)) {
            Toast.makeText(getContext(), "您还未安装QQ客户端!", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 获取分享的图片资源
     *
     * @return
     */
    private UMImage getShareImage(String imageUrl) {
        // 设置分享图片
        UMImage img;
        if (!TextUtils.isEmpty(imageUrl)) {
            img = new UMImage(getContext(), imageUrl);
        } else {
            img = null; //new UMImage(getContext(), R.drawable.ic_launcher);
        }
        return img;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 坑：只能回调到activity的onActivityResult，只好activity中加上 UmengFragment.newInstance(this).onActivityResult(requestCode, resultCode, data);
         * 只有QQ
         */
        //第三方登录回调
        UMShareAPI.get(getContext()).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //防止内存泄漏
        UMShareAPI.get(getContext()).release();
    }


}
